<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>商品列表 - 网上跳蚤市场</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body class="products-page">
<div th:replace="layout :: .nav"></div>
<div class="container">
    <section>
        <h2>商品列表</h2>

        <div class="search-bar">
            <input type="text" id="searchInput" placeholder="搜索商品...">
            <button id="searchBtn" class="btn">搜索</button>
        </div>

        <div class="category-filter">
            <button class="category-btn active" data-id="0">全部</button>
            <!-- 分类按钮将通过JavaScript加载 -->
        </div>

        <div class="card">
            <div id="productList"></div>
        </div>

        <div id="pagination" class="pagination"></div>
    </section>
</div>

<script>
    // 全局变量
    let currentCategoryId = 0;
    let currentKeyword = null;
    let page = 0, size = 8;

    // 加载分类
    async function loadCategories() {
        try {
            const res = await fetch('/api/categories');
            const categories = await res.json();

            const categoryFilter = document.querySelector('.category-filter');
            categoryFilter.innerHTML = '<button class="category-btn active" data-id="0">全部</button>';

            categories.forEach(category => {
                const btn = document.createElement('button');
                btn.className = 'category-btn';
                btn.setAttribute('data-id', category.id);
                btn.textContent = category.name;
                categoryFilter.appendChild(btn);
            });

            // 添加分类点击事件
            document.querySelectorAll('.category-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    // 移除所有分类的active状态
                    document.querySelectorAll('.category-btn').forEach(el => {
                        el.classList.remove('active');
                    });

                    // 添加当前分类的active状态
                    this.classList.add('active');

                    // 更新当前分类ID
                    currentCategoryId = parseInt(this.getAttribute('data-id'));
                    currentKeyword = null; // 清除搜索关键词
                    document.getElementById('searchInput').value = '';

                    // 重置页码并重新加载商品
                    page = 0;
                    loadProducts();
                });
            });
        } catch (e) {
            console.error('加载分类失败:', e);
        }
    }

    // 加载商品
    async function loadProducts() {
        try {
            let url = `/api/products/page?page=${page}&size=${size}`;

            if (currentCategoryId && currentCategoryId !== 0) {
                url = `/api/products/category/${currentCategoryId}?page=${page}&size=${size}`;
            } else if (currentKeyword) {
                url = `/api/products/search?keyword=${encodeURIComponent(currentKeyword)}&page=${page}&size=${size}`;
            }

            console.log("加载商品URL:", url);
            const response = await fetch(url);
            const data = await response.json();
            console.log("获取到的商品数据:", data);

            const productsContainer = document.getElementById('productList');

            if (!data.content || data.content.length === 0) {
                productsContainer.innerHTML = '<div class="no-products">没有找到符合条件的商品</div>';
                document.getElementById('pagination').innerHTML = '';
                return;
            }

            // 创建商品网格
            let gridHtml = '<div class="products-grid">';

            data.content.forEach(product => {
                // 只显示上架中的商品
                if (product.status === 'on_sale') {
                    // 格式化价格
                    const price = product.price ? parseFloat(product.price).toFixed(2) : '0.00';

                    // 获取评分
                    let buyerScore = 0;
                    if (product.additionalProperties && product.additionalProperties.buyerResponseScore) {
                        buyerScore = product.additionalProperties.buyerResponseScore;
                    } else if (typeof product.buyerResponseScore !== 'undefined') {
                        // 备选方案：直接从product对象中获取评分
                        buyerScore = product.buyerResponseScore;
                    }

                    // 处理图片URL
                    let imageUrl = product.imageUrl;
                    if (imageUrl && !imageUrl.startsWith('http') && !imageUrl.startsWith('/')) {
                        imageUrl = '/' + imageUrl;
                    }

                    const imageHtml = imageUrl ?
                        `<img src="${imageUrl}" alt="${product.name}" onerror="this.onerror=null; this.src='https://via.placeholder.com/300x200?text=暂无图片'; console.log('图片加载失败，使用占位图');">` :
                        '<div class="no-image">暂无图片</div>';

                    // 生成商品详情链接
                    const detailUrl = `product-detail?id=${product.id}`;

                    gridHtml += `
                    <a href="${detailUrl}" class="product-card" onclick="handleProductClick(event, ${product.id})">
                        <div class="product-img-container">
                            ${imageHtml}
                        </div>
                        <div class="product-info">
                            <h3 title="${product.name}">${product.name}</h3>
                            <div class="price">¥${price}</div>
                            <div class="rating">${buyerScore > 0 ? '★ ' + buyerScore.toFixed(1) : '暂无评分'}</div>
                        </div>
                    </a>
                `;
                }
            });

            gridHtml += '</div>';
            productsContainer.innerHTML = gridHtml;

            // 渲染分页
            renderPagination(data.totalPages);

        } catch (error) {
            console.error('加载商品失败:', error);
            document.getElementById('productList').innerHTML = '<div class="error-msg">加载商品失败，请刷新重试</div>';
        }
    }

    // 渲染分页控件
    function renderPagination(totalPages) {
        const paginationContainer = document.getElementById('pagination');
        paginationContainer.innerHTML = '';

        if (totalPages <= 1) {
            return;
        }

        let paginationHtml = '';

        // 上一页按钮
        paginationHtml += `<button onclick="changePage(${page - 1})" ${page === 0 ? 'disabled' : ''}>上一页</button>`;

        // 页码按钮
        for (let i = 0; i < totalPages; i++) {
            paginationHtml += `<button onclick="changePage(${i})" class="${i === page ? 'active' : ''}">${i + 1}</button>`;
        }

        // 下一页按钮
        paginationHtml += `<button onclick="changePage(${page + 1})" ${page === totalPages - 1 ? 'disabled' : ''}>下一页</button>`;

        paginationContainer.innerHTML = paginationHtml;
    }

    // 切换页码
    function changePage(newPage) {
        if (newPage < 0) return;
        page = newPage;
        loadProducts();
    }

    // 添加搜索功能
    document.getElementById('searchBtn').addEventListener('click', function() {
        const keyword = document.getElementById('searchInput').value.trim();
        if (keyword) {
            currentKeyword = keyword;
            currentCategoryId = 0; // 重置分类

            // 重置分类按钮状态
            document.querySelectorAll('.category-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            document.querySelector('.category-btn[data-id="0"]').classList.add('active');

            // 重置页码并加载搜索结果
            page = 0;
            loadProducts();
        }
    });

    // 添加回车搜索功能
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            document.getElementById('searchBtn').click();
        }
    });

    // 初始加载
    loadCategories();
    loadProducts();

    // 商品点击处理函数
    function handleProductClick(event, productId) {
        console.log("点击商品:", productId);
        // 阻止默认行为，手动跳转
        event.preventDefault();

        // 构建商品详情页面URL
        const detailUrl = `product-detail?id=${productId}`;
        console.log("跳转到:", detailUrl);

        // 手动跳转到商品详情页面
        window.location.href = detailUrl;
    }
</script>

<style>
    /* 搜索栏样式 */
    .search-bar {
        display: flex;
        margin-bottom: 20px;
    }

    .search-bar input {
        flex: 1;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 4px 0 0 4px;
    }

    .search-bar button {
        padding: 10px 20px;
        background-color: #ff6b6b;
        color: white;
        border: none;
        border-radius: 0 4px 4px 0;
        cursor: pointer;
    }

    .search-bar button:hover {
        background-color: #ff5252;
    }

    /* 分类过滤器样式 */
    .category-filter {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-bottom: 20px;
    }

    .category-btn {
        padding: 8px 15px;
        background-color: #f5f5f5;
        border: 1px solid #ddd;
        border-radius: 20px;
        cursor: pointer;
    }

    .category-btn:hover {
        background-color: #eee;
    }

    .category-btn.active {
        background-color: #ff6b6b;
        color: white;
        border-color: #ff6b6b;
    }

    /* 商品网格样式 */
    .products-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        grid-template-rows: repeat(2, 1fr);
        gap: 20px;
        margin-top: 10px;
        height: 100%;
    }

    .product-card {
        border: 1px solid #eee;
        border-radius: 8px;
        overflow: hidden;
        transition: transform 0.2s, box-shadow 0.2s;
        background-color: white;
        cursor: pointer;
        display: flex;
        flex-direction: column;
        text-decoration: none;
        color: inherit;
        height: 100%;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    }

    .product-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }

    .product-img-container {
        width: 100%;
        height: 0;
        padding-bottom: 65%;
        overflow: hidden;
        position: relative;
        background-color: #f9f9f9;
    }

    .product-img-container img {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .no-image {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        color: #999;
        font-style: italic;
    }

    .product-info {
        padding: 12px;
        display: flex;
        flex-direction: column;
        flex: 1;
    }

    .product-info h3 {
        margin: 0 0 8px 0;
        font-size: 15px;
        height: 36px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        color: #333;
    }

    .price {
        color: #ff6b6b;
        font-weight: bold;
        font-size: 16px;
        margin-top: auto;
    }

    .rating {
        color: #ffc107;
        margin-top: 5px;
        font-size: 14px;
    }

    /* 分页样式 */
    .pagination {
        display: flex;
        justify-content: center;
        margin-top: 20px;
        gap: 5px;
    }

    .pagination button {
        padding: 8px 12px;
        border: 1px solid #ddd;
        background-color: #fff;
        cursor: pointer;
        border-radius: 4px;
    }

    .pagination button:hover {
        background-color: #f5f5f5;
    }

    .pagination button.active {
        background-color: #ff6b6b;
        color: white;
        border-color: #ff6b6b;
    }

    .pagination button:disabled {
        cursor: not-allowed;
        opacity: 0.5;
    }

    /* 无商品提示 */
    .no-products {
        text-align: center;
        padding: 30px;
        color: #999;
        font-style: italic;
    }
</style>
</body>
</html> 